import pymysql
from flask import Flask, render_template, request, redirect, session
from mysql import Mysql
from models import Session, User

app = Flask(__name__)
app.config['SECRET_KEY'] = 'FQ34A;MOKIDZSKIGMW4I5O'
conn = pymysql.connect(host='localhost', port=3306, database='biyesheji', user='root', password='123456')


def verify(username, password):
    with Session() as s:
        from sqlalchemy import and_
        one = s.query(User).filter(and_(User.username == username, User.password == password)).first()
        if one is not None:
            print(f'登陆验证成功, 用户信息: {one=}')
        else:
            print(f'登陆验证失败, 用户未找到')
        return one


@app.route('/index')
def name():
    page = request.args.get('page')
    if not page or int(page) == 0:
        page = 1
    db = Mysql()
    keyword = request.args.get('keyword')
    items = db.getItems(page, keyword)
    page_range = range(int(page) - 3, int(page) + 2)
    if int(page) < 4:
        page_range = range(1, int(page) + 4)
    return render_template('index.html', items=items, page=int(page), prange=page_range)


@app.route('/new')
def new():
    return render_template('register.html', user={})


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    if request.method == 'POST':
        # 获取post方法发送的参数
        username = request.form.get('username')
        password = request.form.get('password')
        code = request.form.get('code')
        if session.get('rcode').lower() != code.lower():
            return render_template('login.html', error='验证码错误')
        if verify(username, password):
            session['username'] = username
            return redirect('/index')
        else:
            return render_template('login.html', error='用户名或密码错误')


@app.route('/register', methods=['GET', 'POST'])
def register():
    username = request.args.get('username')
    password = request.args.get('password')
    if username:
        with Session() as s:
            s.add(User(username, password))
            s.commit()
            return redirect('/login')
    else:
        return render_template('register.html', user={}, error='用户名或密码不能为空')


from utils import Captcha


@app.route('/captcha')
def captcha():
    c = Captcha()
    generated_code = c.make_captcha()
    print(f'生成的验证码 {generated_code}')
    session['rcode'] = generated_code
    with app.open_resource('static/captcha.png', 'rb') as f:
        pic = f.read()
    return pic


@app.before_request
def interceptor():
    print('拦截器 ' + request.url)
    if session.get('username') or request.url.endswith(
            '/login') or '/static/' in request.url or '/captcha' in request.url or '/new' in request.url:
        pass
    else:
        return redirect('/login')


app.run(host='0.0.0.0', port=5555, debug=True)
